<template>
	<view>
		<u-radio-group style="margin: 20px;" v-if="pdfUrlList.length" v-model="value" @change="radioChange">
			<view style="margin-right: 15rpx;">先择工序文件：</view>
			<u-radio 
				v-for="(item, index) in pdfUrlList" :key="index" 
				:name="item.pdfUrl"
				 :disabled="false"
			>
				{{item.tprocessOrder}}
			</u-radio>
		</u-radio-group>
		<web-view v-else :webview-styles="webviewStyles" :src="pdfUrl"></web-view>
		<u-toast ref="uToast" />
		<!-- <view class="countDown">
			<u-line-progress active-color="#2979ff" :percent="70"></u-line-progress>
		</view> -->
		<!-- <text class="countDown" @click="evalJs" v-if="!readTag && pdfUrl">
			阅读倒计时{{timeCount}}秒
		</text> -->
	</view>
</template>

<script>
	import { getPdfAndVideo, setUserSopFile,findsectionNo } from '../utils/index.js'
	export default {
		data() {
			return {
				webviewStyles: {
					progress: {
						color: '#FF3333'
					}
				},
				pdfUrl:'',										//获取到PDF的url地址
				pdfUrlList:[],									//获取到PDF1的url地址
				sectionNum: '',									//工段编号
				workCenter: '',									//车间
				deviceBardcode: '',								//数控车间的设备条码
				timer: '',
				readTag: 1,
				timeCount: 60,
				value: ''
			}
		},
		// 从页面存储获取到 routeInfo 数据，再传给 this.getPdf 函数来获取到pdfUrl字符串
		onLoad() {
			// if(sessionStorage.getItem('workCenter') == '数控车间') return
			// const sopBarcode = sessionStorage.getItem('routeInfo')
			// this.getPdf(sopBarcode)
		},
		//两种情况：
		//当readTag为1时，代表工人已经阅读完毕文档，这时进入else语句，发送已经阅读完毕的请求
		//当readTag为0时，代表工人没有阅读文档，这时进入if语句，这时设置readTag为0，并且记录开始时间startTime
		onShow() {
			if(sessionStorage.getItem('workCenter') == '数控车间' && sessionStorage.getItem('deviceBarcode')==null) {
				console.log('数控车间工段，没有设备条码')
				return
			}
			const sopBarcode = sessionStorage.getItem('routeInfo')
			this.getPdf(sopBarcode)
			if(!Number(sessionStorage.getItem('readTag'))) {
				sessionStorage.setItem("readTag", 0)
				this.readTag = 0
				this.timeCount = 60
				sessionStorage.setItem("startTime", Math.round(new Date().getTime()/1000))
				console.log('进入时间',Math.round(new Date().getTime()/1000));
			} else {
				this.postReadTag()
			}
			uni.setNavigationBarTitle({	
				title: '操作指导文档'
			});
		},
		//当从readPdf页面切出去时，触发onHide()函数，记录时间stopTime存储在页面中
		//将stopTime与页面存储的startTime作差，得出duration
		onHide() {
			console.log('离开');
			let deviceBarcode = sessionStorage.getItem('deviceBarcode')
			if(sessionStorage.getItem('workCenter') == '数控车间' && sessionStorage.getItem('deviceBarcode')==null){
				console.log('数控车间,deviceBarcode为空')
				return
			}
			sessionStorage.setItem("stopTime", Math.round(new Date().getTime()/1000))	
			console.log('离开时间',Math.round(new Date().getTime()/1000));
			const duration = sessionStorage.getItem('stopTime') - sessionStorage.getItem('startTime')
			console.log(duration);
			if(this.pdfUrl) {
				// 停留60秒
				if(duration >= 60) {
					sessionStorage.setItem("readTag", 1)
					this.postReadTag()
				} else {
					alert('请观看文档！')
				}
				clearInterval(this.timer)
			} else {
				console.log('秒',this.timeCount);
				if(this.timeCount > 0){
					alert('请观看文档！')
					clearInterval(this.timer)
					uni.setNavigationBarTitle({
						title: '操作指导文档'
					});
					return
				}
				if(duration >= 1) {
					sessionStorage.setItem("readTag", 1)
					this.postReadTag()
				} else {
					alert('请观看文档！')
				}
			}
		},
		methods: {
			radioChange(e){
				console.log(e);
				this.pdfUrl = e
				this.pdfUrlList = []
			},
			async findsectionNo(value){
				this.sectionNum = value.substring(0,6)
				const { data } = await findsectionNo({sectionNo:this.sectionNum})
				if(data.data.workCenter == '数控车间'){
					this.workCenter = data.data.workCenter
					this.pdfUrlList.forEach((item,index)=>{
						if(item){
							if(item.pdfUrl){
								if(index == 0 && this.handleName(item.pdfUrl).split('.')[1] == 'xlsx'){
									console.log('第一个为xlsx,不需要额外下载')
								} else {
									this.downLoad(item.pdfUrl,item.technologyNo)
								}
							}
							if(item.pdfUrl1){this.downLoad(item.pdfUrl1,item.technologyNo)}
						}
					})
				}
			},
			downLoad(url,technologyNo){
				uni.showLoading({
					title:"正在请求数据"
				});
				uni.request({
					url, //获取文件流的请求路径
					responseType: "arraybuffer",  
					success: (response) => {
						uni.hideLoading();
						if(!response){
							uni.showToast({
								title:"下载失败",
								duration:2000
							});
						}
						let blob = new Blob([response.data]);
						let downloadElement = document.createElement("a");
						let href = window.URL.createObjectURL(blob); //创建下载的链接
						downloadElement.href = href;
						downloadElement.download = technologyNo + '产品编号'+'__' + this.handleName(url); //下载后文件名
						document.body.appendChild(downloadElement);
						downloadElement.click(); //点击下载
						document.body.removeChild(downloadElement); //下载完成移除元素
						window.URL.revokeObjectURL(href); //释放掉blob对象
					}
				})
			},
			handleName(val){
				return val.split('/')[5]
			},
			// 获取PDF文档的URL地址，当文件为空时提示，不为空时返回url地址
			async getPdf(value) {
				const query = {
					sopBarcode:value,
					deviceBardcode: sessionStorage.getItem('deviceBarcode')
				}
				const { data } =await getPdfAndVideo(query)
				const errMsg = data.msg
				if(data.code == '69') {
					alert(errMsg)
				} else {
					if(!data.data.length) return this.$refs.uToast.show({
					    		title: '该编码没有维护SOP文件！',
					    		type: 'error',
					    		icon: true
					    	})
					// this.pdfUrl = '/hybrid/html/web/viewer.html?file='+encodeURIComponent(value1)pdfUrl
					// this.pdfUrl = data.data[0]?data.data[0].pdfUrl:''						//将获取到的PDF文档的URL地址赋值给pdfUrl变量
					if(sessionStorage.getItem('workCenter') != '数控车间'){	
						const process = sessionStorage.getItem('routeInfo').slice(-2) // 工序
						if(data.data.length == 1 && !data.data[0].tprocessOrder){ // 文件列表只有一条, 也没有工序的直接打开
							this.pdfUrl = data.data[0]?data.data[0].pdfUrl:''
						} else{
						    const arr = data.data.filter(item => process == item.tprocessOrder)// 判断文件列表的工序和当前页面工序一致就直接打开文件)
							if(arr.length == 1){
								this.pdfUrl = arr[0].pdfUrl ? arr[0].pdfUrl:''
							} else{
								console.log('匹配不到');
								this.pdfUrlList = data.data		
							}
						}
					} else {
						this.pdfUrl = data.data[0]?data.data[0].pdfUrl:''	
						this.pdfUrlList = data.data
					}
					console.log('data',data)
					this.findsectionNo(value)
					let that = this
					if(data.data[0]){ 
						// clearInterval(that.timer)
						that.timer = setInterval(function(){
							that.timeCount--
							uni.setNavigationBarTitle({
								title: '操作指导文档' + '（阅读倒计时：' + that.timeCount +'）'
							});
							if(that.timeCount<0){
								clearInterval(that.timer)
								that.postReadTag()
								that.readTag = 1
								uni.setNavigationBarTitle({
									title: '操作指导文档'
								});
							}
							console.log(that.timer)
						},1000)
					}
				}
			},
			// 向后台发送是否已经阅读完成的消息
			async postReadTag() {
				const query = {
					sopBarcode:sessionStorage.getItem('routeInfo'),
					deviceBardcode: sessionStorage.getItem('deviceBarcode')
				}
				const { data } = await setUserSopFile(query)
			},
			// downloadPdfClick(){
			// 	// 下载情景1:h5内嵌app,通过分享给朋友的方式进行下载
			// 	if(this.from == 'app'){
			// 		let item = 'http://自己的域名/hybrid/html/web/pdf.html?shareUrl='+encodeURIComponent(this.bgUrl)
			// 					+'&shareTitle=PDF文件';
			// 		window.open(item);
			// 		return;
					
			// 	}else if(this.from == 'wx wq'){
			// 	// 下载情景2:h5内嵌微信小程序,从h5页面跳转到小程序页面后,然后通过调用小程序原生API进行下载
			// 	// 注意: 先要引入微信jssdk  [命令: npm install jweixin-module]
			// 		// this.$wx.miniProgram.navigateTo({
			// 		// 	url: '/pages/pdf/pdf_download?pdf='+ encodeURIComponent(this.bgUrl) //小程序页面链接
			// 		// });
			// 	}
				
			// }
		}
	}
</script>

<style>
	.countDown{
		position: fixed;
		bottom: 160rpx;
		right: 50rpx;
		width: 150rpx;
		height: 80rpx;
		font-size: 20rpx;
		text-align: center;
		border: 1rpx solid #909399;
		padding: 10rpx;
		border-radius: 10rpx;
	}
</style>
